package com.cf.web.interceptor;

import com.cf.web.autoconfigure.WebCommonProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * game-server-ZmmHandlerInterceptor
 * 自己系统的Interceptor接口
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/6/13 下午 01:21
 */
public abstract class ZmmHandlerInterceptor implements HandlerInterceptor {


    @Autowired
    private WebCommonProperty webCommonProperty;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        if (ignore(requestURI)) {
            //如果url在配置的忽略范围内，不拦截处理！
            return true;
        } else {
            return preHandleInner(request, response, handler);
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    protected abstract boolean preHandleInner(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException;

    /**
     * 需要拦截的地址
     *
     * @return
     */
    public abstract List<String> matchPathPatterns();

    protected boolean ignore(String path) {
        List<String> ignores = webCommonProperty.getIgnore();
        if (ignores == null)
            return true;

        for (String ignore : ignores) {
            boolean start = path.startsWith(ignore);
            if (start)
                return start;
        }

        return false;
    }


}
